from flask import Blueprint, request, jsonify
from app.models import db, Student, Teacher, Admin
from app.utils import token_required
import datetime
from flask import current_app
import jwt
from werkzeug.security import check_password_hash

admin_api_bp = Blueprint('admin_api', __name__)

@admin_api_bp.route('/login', methods=['POST'])
def admin_login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    admin = Admin.query.filter_by(username=username).first()
    if admin and admin.check_password(password):
        token = jwt.encode({
            'admin_id': admin.id,
            'role': 'admin',
            'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=2)
        }, current_app.config['SECRET_KEY'], algorithm='HS256')
        if isinstance(token, bytes):
            token = token.decode('utf-8')
        return jsonify({'code': 200, 'msg': '登录成功', 'token': token, 'role': 'admin'})
    else:
        return jsonify({'code': 401, 'msg': '用户名或密码错误'}), 401

@admin_api_bp.route('/pending-teachers', methods=['GET'])
@token_required
def get_pending_teachers(current_user):
    if not isinstance(current_user, Admin):
        return jsonify({'code': 403, 'msg': '权限不足'}), 403
    
    pending_teachers = Teacher.query.filter_by(
        approval_status='pending'
    ).order_by(Teacher.created_at.desc()).all()
    
    teachers = []
    for teacher in pending_teachers:
        teachers.append({
            'id': teacher.id,
            'username': teacher.username,
            'name': teacher.name,
            'gender': teacher.gender,
            'department': teacher.department,
            'phone': teacher.phone,
            'email': teacher.email,
            'created_at': teacher.created_at.strftime('%Y-%m-%d %H:%M:%S') if teacher.created_at else ''
        })
    
    return jsonify({'code': 200, 'teachers': teachers})

@admin_api_bp.route('/approved-teachers', methods=['GET'])
@token_required
def get_approved_teachers(current_user):
    if not isinstance(current_user, Admin):
        return jsonify({'code': 403, 'msg': '权限不足'}), 403
    
    approved_teachers = Teacher.query.filter_by(
        approval_status='approved'
    ).order_by(Teacher.approval_time.desc()).all()
    
    teachers = []
    for teacher in approved_teachers:
        # 获取审核人信息
        approver = Admin.query.get(teacher.approved_by) if teacher.approved_by else None
        
        teachers.append({
            'id': teacher.id,
            'username': teacher.username,
            'name': teacher.name,
            'gender': teacher.gender,
            'department': teacher.department,
            'phone': teacher.phone,
            'email': teacher.email,
            'approval_time': teacher.approval_time.strftime('%Y-%m-%d %H:%M:%S') if teacher.approval_time else '',
            'approved_by_name': approver.name if approver else '系统'
        })
    
    return jsonify({'code': 200, 'teachers': teachers})

@admin_api_bp.route('/rejected-teachers', methods=['GET'])
@token_required
def get_rejected_teachers(current_user):
    if not isinstance(current_user, Admin):
        return jsonify({'code': 403, 'msg': '权限不足'}), 403
    
    rejected_teachers = Teacher.query.filter_by(
        approval_status='rejected'
    ).order_by(Teacher.approval_time.desc()).all()
    
    teachers = []
    for teacher in rejected_teachers:
        # 获取审核人信息
        approver = Admin.query.get(teacher.approved_by) if teacher.approved_by else None
        
        teachers.append({
            'id': teacher.id,
            'username': teacher.username,
            'name': teacher.name,
            'gender': teacher.gender,
            'department': teacher.department,
            'phone': teacher.phone,
            'email': teacher.email,
            'approval_time': teacher.approval_time.strftime('%Y-%m-%d %H:%M:%S') if teacher.approval_time else '',
            'approved_by_name': approver.name if approver else '系统'
        })
    
    return jsonify({'code': 200, 'teachers': teachers})

@admin_api_bp.route('/students', methods=['GET'])
@token_required
def get_all_students(current_user):
    if not isinstance(current_user, Admin):
        return jsonify({'code': 403, 'msg': '权限不足'}), 403
    
    students = Student.query.order_by(Student.created_at.desc()).all()
    
    student_list = []
    for student in students:
        student_list.append({
            'id': student.id,
            'username': student.username,
            'name': student.name,
            'gender': student.gender,
            'grade': student.grade,
            'class_name': student.class_name,
            'department': student.department,
            'phone': student.phone,
            'email': student.email,
            'created_at': student.created_at.strftime('%Y-%m-%d %H:%M:%S') if student.created_at else ''
        })
    
    return jsonify({'code': 200, 'students': student_list})

@admin_api_bp.route('/approve-teacher/<int:teacher_id>', methods=['POST'])
@token_required
def approve_teacher(current_user, teacher_id):
    if not isinstance(current_user, Admin):
        return jsonify({'code': 403, 'msg': '权限不足'}), 403
    
    data = request.get_json()
    action = data.get('action')  # 'approve' or 'reject'
    
    teacher = Teacher.query.filter_by(id=teacher_id).first()
    if not teacher:
        return jsonify({'code': 404, 'msg': '教师不存在'}), 404
    
    if action == 'approve':
        teacher.is_approved = True
        teacher.approval_status = 'approved'
        teacher.approval_time = datetime.datetime.utcnow()
        teacher.approved_by = current_user.id
        msg = '审核通过'
    elif action == 'reject':
        teacher.is_approved = False
        teacher.approval_status = 'rejected'
        teacher.approval_time = datetime.datetime.utcnow()
        teacher.approved_by = current_user.id
        msg = '审核拒绝'
    else:
        return jsonify({'code': 400, 'msg': '无效的操作'}), 400
    
    db.session.commit()
    return jsonify({'code': 200, 'msg': msg})

@admin_api_bp.route('/teacher-stats', methods=['GET'])
@token_required
def get_teacher_stats(current_user):
    if not isinstance(current_user, Admin):
        return jsonify({'code': 403, 'msg': '权限不足'}), 403
    
    total_students = Student.query.count()
    pending_teachers = Teacher.query.filter_by(approval_status='pending').count()
    approved_teachers = Teacher.query.filter_by(approval_status='approved').count()
    rejected_teachers = Teacher.query.filter_by(approval_status='rejected').count()
    # 教师总数只包括待审核和已通过的教师，不包括被拒绝的教师
    total_teachers = pending_teachers + approved_teachers
    
    return jsonify({
        'code': 200,
        'stats': {
            'total_students': total_students,
            'total': total_teachers,
            'pending': pending_teachers,
            'approved': approved_teachers,
            'rejected': rejected_teachers
        }
    }) 